package com.xunshangwang.pinhaohuo.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.entity.Order;
import com.xunshangwang.pinhaohuo.entity.WechatPay;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.tools.CommonTool;
import com.xunshangwang.pinhaohuo.tools.PayHelper;
import com.xunshangwang.pinhaohuo.widgets.LoadLayout;
import com.xunshangwang.pinhaohuo.widgets.RadioFrameGroup;

import org.json.JSONObject;
import org.w3c.dom.Text;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import cz.msebera.android.httpclient.Header;
import tool.library.ToastTool;

/**
 * Created by xzp on 16/3/16.
 */
public class OrderDetailActivity extends BaseActivity implements View.OnClickListener{
    private String mId;
    private boolean mJumpToGroup;
    private Order mOrder;
    private View mRootView;
    private LoadLayout mLoad;
    private TextView mReceiveNameText,mPhoneText,mAddressText;
    private ImageView mShopImage,mGoodsImage;
    private TextView mGoodsNameText,mShopNameText;
    private TextView mOrderStatusText;
    private TextView mGoodsPriceText,mOrderPriceText;
    private TextView mOrderSnText,mPayWayText,mCreateTimeText;
    private String[] mStatusArray;
    private View mPayPanel;
    private RadioFrameGroup mPayWayGroup;
    private View mAfterPayServiceBtn;
    private PayHelper mPayHelper;
    private PayHelper.OnPayCallback mCallBack=new PayHelper.OnPayCallback() {
        @Override
        public void onPayComplete(int payWay, int code, String msg) {
            mLoad.finishLoad();
            if(msg!=null)
                ToastTool.showToast(msg);
            if(code==PayHelper.PAY_SUCCESS){
                mPayPanel.setVisibility(View.GONE);
                mPayWayText.setVisibility(View.VISIBLE);
                mAfterPayServiceBtn.setVisibility(View.VISIBLE);
                setResult(RESULT_OK);
            }else if(code==PayHelper.PAY_FAIL || code==PayHelper.PAY_OTHER){
                finish();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        mId=getIntent().getStringExtra("id");
        mJumpToGroup=getIntent().getBooleanExtra("jumpToGroup",false);
        mStatusArray= getResources().getStringArray(R.array.order_status_array);
        mPayHelper=new PayHelper(this);
        findView();
        initView();
        requestOrderDetail();
    }

    private void findView(){
        mRootView=this.findViewById(R.id.root_view);
        mLoad= (LoadLayout) this.findViewById(R.id.load_layout);
        mReceiveNameText= (TextView) this.findViewById(R.id.receive_name_text);
        mPhoneText= (TextView) this.findViewById(R.id.mobile_phone_text);
        mAddressText= (TextView) this.findViewById(R.id.full_address_text);
        mShopImage= (ImageView) this.findViewById(R.id.shop_image);
        mGoodsImage= (ImageView) this.findViewById(R.id.goods_image);
        mGoodsNameText= (TextView) this.findViewById(R.id.goods_name_text);
        mShopNameText= (TextView) this.findViewById(R.id.shop_name_text);
        mOrderStatusText= (TextView) this.findViewById(R.id.order_status_text);
        mGoodsPriceText= (TextView) this.findViewById(R.id.goods_price_text);
        mOrderPriceText= (TextView) this.findViewById(R.id.order_price_text);
        mOrderSnText= (TextView) this.findViewById(R.id.order_sn_text);
        mPayWayText= (TextView) this.findViewById(R.id.order_pay_way_text);
        mCreateTimeText= (TextView) this.findViewById(R.id.order_create_time_text);
        mPayPanel=this.findViewById(R.id.pay_panel);
        mPayWayGroup= (RadioFrameGroup) this.findViewById(R.id.pay_way_group);
        mAfterPayServiceBtn=this.findViewById(R.id.after_pay_service_btn);
    }
    private void initView(){
        mRootView.setVisibility(View.GONE);
        mAfterPayServiceBtn.setOnClickListener(this);
        this.findViewById(R.id.order_pay_btn).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        final int id=view.getId();
        switch (id){
            case R.id.after_pay_service_btn:
                startActivity(new Intent(this,AfterSaleServiceActivity.class));
                break;
            case R.id.order_pay_btn:
                if(mPayWayGroup.getCheckedId()==R.id.wechat_radio_btn){
                    if(!mPayHelper.isWechatSupport()){
                        ToastTool.showToast(getResources().getString(R.string.wechat_not_support_msg));
                        break;
                    }
                }else if(mPayWayGroup.getCheckedId()==R.id.alipay_radio_btn){
                    ToastTool.showToast(getResources().getString(R.string.alipay_not_support_msg));
                    break;
                }
                requestPay();
                break;
        }
    }
    private void requestPay(){
        if(mPayWayGroup.getCheckedId()==R.id.wechat_radio_btn){
            StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=appwxpay");
            builder.append("&token="+getMainApplication().getToken());
            builder.append("&order_id="+mId);
            HttpTool.get(this, builder.toString(), new JsonHttpHandler<WechatPay>() {
                @Override
                public void onStart() {
                    super.onStart();
                    mLoad.startLoad();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, WechatPay errorResponse) {
                    super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                    mLoad.finishLoad();
                }

                @Override
                public WechatPay parseData(JSONObject object) throws Throwable {
                    return JSON.parseObject(object.getString("param"),WechatPay.class);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, WechatPay response) {
                    if(response==null)
                    {
                        ToastTool.showToast("订单信息获取失败,请重试");
                        mLoad.finishLoad();
                        return;
                    }
                    mPayHelper.startWechatPay(response,mCallBack);
                }
            });
        }
    }
    private void requestOrderDetail(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=getorder");
        builder.append("&token="+getMainApplication().getToken());
        builder.append("&order_id=" + mId);
        HttpTool.get(this, builder.toString(), new JsonHttpHandler<Order>() {
            @Override
            public Order parseData(JSONObject object) throws Throwable {
                return JSON.parseObject(object.getString("order"),Order.class);
            }

            @Override
            public void onStart() {
                super.onStart();
                mLoad.startLoad();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mLoad.finishLoad();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Order errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                if(mOrder==null)
                    finish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Order response) {
                mOrder=response;
                if(response!=null){
                    if(mJumpToGroup && !TextUtils.equals("0",response.getGroup_order_id())){
                        Intent intent=new Intent(OrderDetailActivity.this,GroupDetailActivity.class);
                        intent.putExtra("id",response.getGroup_order_id());
                        startActivity(intent);
                        finish();
                        return;
                    }
                    mReceiveNameText.setText(response.getReceive_name());
                    mAddressText.setText(response.getShipping_address());
                    mPhoneText.setText(response.getMobile());
                    if(response.getOrder_shop()!=null) {
                        Glide.with(OrderDetailActivity.this).load(response.getOrder_shop().getShop_face()).centerCrop().into(mShopImage);
                        mShopNameText.setText(response.getOrder_shop().getShop_name());
                    }
                    Glide.with(OrderDetailActivity.this).load(response.getOrder_goods().getImage_url()).centerCrop().into(mGoodsImage);
                    mGoodsNameText.setText(response.getOrder_goods().getGoods_name());
                    mGoodsPriceText.setText(CommonTool.getPriceFormatString(OrderDetailActivity.this, response.getOrder_goods(), response.getGroup_buy()));
                    DecimalFormat format=new DecimalFormat("0.00");
                    mOrderPriceText.setText("￥" + format.format(response.getOrder_amount()) + "(免运费)");
                    SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    mCreateTimeText.setText("下单时间 : "+dateFormat.format(new Date(response.getOrder_time()*1000)));
                    mOrderSnText.setText("订单编号 : "+response.getOrder_sn());
                    if(response.getOrder_status()>=0 && response.getOrder_status()<mStatusArray.length){
                        mOrderStatusText.setText(mStatusArray[response.getOrder_status()]);
                    }
                    if(response.getOrder_status()==0) {
                        mPayWayText.setVisibility(View.GONE);
                        mPayPanel.setVisibility(View.VISIBLE);
                        mPayWayGroup.check(R.id.wechat_radio_btn);
                        mAfterPayServiceBtn.setVisibility(View.GONE);
                    }else {
                        mPayPanel.setVisibility(View.GONE);
                        mPayWayText.setVisibility(View.VISIBLE);
                        mAfterPayServiceBtn.setVisibility(View.VISIBLE);
                    }
                    mRootView.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        mPayHelper.unRegisterCallback();
        super.onDestroy();
    }
}
